import glob

import datetime
import re
from os import stat, makedirs, rename, umask
from subprocess import Popen
import subprocess
from stat import *

import socket
testing = socket.gethostname() != 'pc.cs.purdue.edu'

def runnable(f):
    try:
        mode = stat(f).st_mode  # get mode bits of script file
    except OSError:
        return False
    if (mode & 5) != 5: # check for +rx bit set for world
        return False
    if S_ISDIR(mode):
        return False
    return True

excluded_endswith = [ '~' ]
excluded_in = [ 'view3d', 'view2d', 'viewse', 'viewso', 'strategery' ]

def ignoreFile(f):
    if '.' in f or '-' in f:
        return True
    for t in excluded_endswith:
        if f.endswith(t):
            return True
    for t in excluded_in:
        if t in f:
            return True
    return False

##
# Work starts here...
#
db(db.match.id > 0).delete()
db(db.competitor.id > 0).delete()

if testing:
    TESTS_DIR = 'applications/' + request.application + '/private/tests'
    for f in glob.glob(TESTS_DIR + "/*-*"):
        file = f.split("/")[-1]
        (user, player) = file.split("-")
        print "%s/%s" % (user, player)
        db.competitor.insert(status='ready', name_user=user, name_player=player)
else:
    rows = db(db.auth_user.id > 0).select(db.auth_user.ALL)
    for row in rows:
        for f in glob.glob("/homes/%s/icypc/*" % row.username):
            if not runnable(f):
                continue
            if ignoreFile(f):
                continue
            player = f.split("/")[-1]
            print row.username, player
            db.competitor.insert(status='ready', name_user=row.username, name_player=player)

